package name.vaccari.matteo.tai.chat.persistence;

import name.vaccari.matteo.tai.chat.domain.Message;
import name.vaccari.matteo.tai.chat.persistence.DatabaseConnector;
import name.vaccari.matteo.tai.chat.persistence.DatabaseExecutor;
import name.vaccari.matteo.tai.chat.persistence.DatabaseMessageRepository;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;

import static java.util.Arrays.asList;


public class DatabaseMessageRepositoryTest {

	private DatabaseMessageRepository repository;
	private DatabaseExecutor executor;

	@Before
	public void setUp() throws Exception {
		DatabaseConnector connector = new DatabaseConnector("tai_chat", 
				"tai_chat", "jdbc:mysql://localhost/tai_chat_test", "com.mysql.jdbc.Driver");
		executor = new DatabaseExecutor(connector);
		executor.execute("delete from messages");
		repository = new DatabaseMessageRepository(executor);
	}
	
	@After
	public void tearDown() {
		executor.closeConnection();
	}

	@Test
	public void testSaveThenLoad() throws Exception {
		assertEquals(asList(), repository.getLatestMessages(100));
		
		Message one = new Message("first message", "pippo");
		repository.save(one);
		assertEquals(asList(one), repository.getLatestMessages(100));
		
		Message two = new Message("second message", "pippo");
		repository.save(two);
		assertEquals(asList(two, one), repository.getLatestMessages(100));
	}
	
	@Test
	public void shouldReturnNoMoreThanXRows() throws Exception {
		Message message = new Message("first message", "pippo");
		repository.save(message);
		repository.save(message);
		repository.save(message);
		assertEquals(3, repository.getLatestMessages(100).size());
		assertEquals(2, repository.getLatestMessages(2).size());
		assertEquals(1, repository.getLatestMessages(1).size());		
	}
}
